<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Stream Chat Demo</title>
    <style>
        body { font-family: sans-serif; margin: 20px; }
        #chat-box {
          border: 1px solid #ccc;
          border-radius: 8px;
          padding: 10px;
          width: 400px;
          height: 300px;
          overflow-y: auto;
        }
        .msg { margin: 5px 0; }
        .user { color: blue; }
        .ai { color: green; }
    </style>
</head>
<body>
<h2>Stream Chat 测试</h2>
<div id="chat-box"></div>
<input id="input" type="text" placeholder="输入消息..." style="width:300px;" />
<button onclick="send()">发送</button>

<script>
    const chatBox = document.getElementById("chat-box");

    function appendMessage(text, cls) {
      const div = document.createElement("div");
      div.className = "msg " + cls;
      div.textContent = text;
      chatBox.appendChild(div);
      chatBox.scrollTop = chatBox.scrollHeight;
      return div; // 返回节点，便于更新
    }

    function send() {
      const input = document.getElementById("input");
      const msg = input.value.trim();
      if (!msg) return;

      appendMessage("你: " + msg, "user");
      input.value = "";

      // AI 回复节点（先空，后续逐步更新）
      const aiDiv = appendMessage("AI: ", "ai");

      // 连接后端 SSE
      const evtSource = new EventSource("/chat/stream?message=" + encodeURIComponent(msg));
      evtSource.onmessage = (e) => {
        aiDiv.textContent += e.data; // 逐步追加
        chatBox.scrollTop = chatBox.scrollHeight;
      };
      evtSource.onerror = () => {
        evtSource.close();
      };
    }
</script>
</body>
</html>
